package com.yimi.yinhepda.views.stockCheck_module;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.Bind;

import com.pda.ym.entity.response.NoDataResponse;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.DifferScanAdapter;
import com.yimi.yinhepda.adapter.DifferScanDealAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.DifferScanTableDao;
import com.yimi.yinhepda.db.table.DifferScanTable;
import com.yimi.yinhepda.entity.DifferScanEntity;
import com.yimi.yinhepda.entity.request.DifferCompleteRequest;
import com.yimi.yinhepda.entity.request.DifferScanRequest;
import com.yimi.yinhepda.entity.request.DifferUploadRequest;
import com.yimi.yinhepda.entity.response.DifferScanResponse;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import org.greenrobot.eventbus.EventBus;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 差异扫描处理界面
 *
 * @author tianjin
 */
public class DifferScanActivity extends BaseInitActivity {
    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    @Bind(R.id.tv_taskno)
    TextView mTvTaskno;
    @Bind(R.id.differ_scan_listview)
    ListView mListView;
    @Bind(R.id.totle_piao)
    TextView mTvTotlePiao;
    @Bind(R.id.totle_jian)
    TextView mTvTotlejian;
    @Bind(R.id.scaned_piao)
    TextView mTvScanedPiao;
    @Bind(R.id.scaned_jian)
    TextView mTvScanedJian;

    /**
     * 异常报告编号
     */
    private String mDifferCode;
    private List<DifferScanEntity> dataList;
    /**
     * 数据展示集合
     */
    private List<HashMap<String, Object>> resultDataList;
    /**
     * 当前操作条目
     */
    private List<HashMap<String, Object>> currentItem = new ArrayList<HashMap<String, Object>>();
    private DifferScanAdapter differScanAdapter;

    /**
     * 新的adapter
     */
    private DifferScanDealAdapter mAdapter;
    /**
     * 全局的数据集合
     */
    private List<DifferScanResponse.DifferScanEntity> mDifferScanDataList = new ArrayList<>();
    /**
     * 总的未上传数量
     */
    private int totalNotUploadNum;
    private DifferScanTableDao mDifferScanTableDao;

    @Override
    public String getPageName() {
        return getString(R.string.page_differ_scan);
    }

    public DifferScanActivity() {
        super(true);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_differ_scan;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTvTitle.setText("差异扫描处理");
        //异常报告编号
        mDifferCode = getIntent().getExtras().getString("taskCode");
        mTvTaskno.setText(String.format(getString(R.string.differ_taskno), mDifferCode));
        //数据表
        mDifferScanTableDao = new DifferScanTableDao();
        //查询未上传数据
        totalNotUploadNum = mDifferScanTableDao.queryNotUploadDataNum();
        mTvNum.setText(totalNotUploadNum + "");
    }

    @Override
    public void initEvent() {
        findViewById(R.id.differ_scan_back).setOnClickListener(this);
        findViewById(R.id.differ_scan_refresh).setOnClickListener(this);
        findViewById(R.id.differ_scan_exec).setOnClickListener(this);
    }

    @Override
    public void initData() {
        loadData();
        //        testData();//写死
    }

    /**
     * 测试,写死
     */
    private void testData() {
        mTvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doScan("123-1");
            }
        });
    }

    /**
     * 访问接口数据
     */
    public void loadData() {
        setScannerEnabled(false);
        showPgDlg("正在加载...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(DifferScanResponse.class)
                .setUrl(Constants.URL_DIFFER_SCAN_DATA)
                .setRequestObject(new DifferScanRequest(mDifferCode))
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        setScannerEnabled(true);
                        dismissPgDlg();
                        if (obj instanceof DifferScanResponse) {
                            DifferScanResponse response = (DifferScanResponse) obj;
                            if (response.getData() == null || response.getData().isEmpty()) {
                                showToast("暂时没有差异数据!");
                                SoundVibratorManager.playSound(2);
                            } else {
                                showDataDetail(response);
                                SoundVibratorManager.playSound(1);
                            }
                        }
                    }
                });
    }

    /**
     * 加载数据到列表
     */
    private void showDataDetail(final DifferScanResponse response) {
        mDifferScanDataList = response.getData();

        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {

                //查询本地子单数据，若不存在子单列表中，则将其插入
                for (DifferScanResponse.DifferScanEntity differScanEntity : mDifferScanDataList) {
                    List<DifferScanTable> differScanTables = mDifferScanTableDao.getDataByDifferCodeAndWaybillNo(mDifferCode, differScanEntity.getWaybillNo());
                    for (DifferScanTable differScanTable : differScanTables) {
                        boolean hasData = false;
                        for (DifferScanResponse.DifferChild childInfo : differScanEntity.getStocktakingDiffreportInventoryVoList()) {
                            if (differScanTable.getWaybillChildNo().equals(childInfo.getWaybillChildNo())) {
                                hasData = true;
                                break;
                            }
                        }
                        if (!hasData) {
                            DifferScanResponse.DifferChild childInfo = new DifferScanResponse.DifferChild();
                            childInfo.setStatus(differScanTable.getScanStatus());
                            childInfo.setWaybillChildNo(differScanTable.getWaybillChildNo());
                            differScanEntity.getStocktakingDiffreportInventoryVoList().add(childInfo);
                        }
                    }
                }

                //判断对应接口数据，数据库中是否已经存在并且已经扫描
                //justResponseDataStatus();

                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                Collections.sort(mDifferScanDataList);
                mAdapter = new DifferScanDealAdapter(DifferScanActivity.this, mDifferScanDataList);
                if (mListView != null) {
                    mListView.setAdapter(mAdapter);
                }

                //总票，件
                mTvTotlePiao.setText(response.getTotalPiao() + "");
                mTvTotlejian.setText(response.getTotalJian() + "");

                //扫描票，件
                mTvScanedPiao.setText(DifferScanResponse.getTotalScannedPiao(mDifferScanDataList) + "");
                mTvScanedJian.setText(DifferScanResponse.getTotalScannedJian(mDifferScanDataList) + "");
            }

            @Override
            public void onError(Throwable throwable) {
                showToast("加载数据失败！");
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    /**
     * 合并数据库的数据
     * 由于返回时，表示数据暂存了，
     * 那么再次进入页面判断对应接口数据，数据库中是否已经存在并且已经扫描
     */
    private void justResponseDataStatus() {
        if (mDifferScanDataList.size() <= 0) {
            return;
        }
        for (DifferScanResponse.DifferScanEntity entity : mDifferScanDataList) {
            //主单
            String waybillNo = entity.getWaybillNo();
            List<DifferScanResponse.DifferChild> childList = entity.getStocktakingDiffreportInventoryVoList();
            if (childList == null || childList.size() <= 0) {
                continue;
            }
            for (DifferScanResponse.DifferChild childItem : childList) {
                //子单
                String childWayBillNo = childItem.getWaybillChildNo();
                //查询数据库，是否已经扫描
                int status = mDifferScanTableDao.findChildWayBillNoStatus(mDifferCode, waybillNo, childWayBillNo);
                if (status == 1) {
                    //数据库中已经扫描的，设置当前数据状态为已扫描
                    childItem.setStatus(1);
                }
            }
        }
    }

    /**
     * 扫描条码回调
     */
    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("扫描条码失败!");
            return;
        } else {
            doScan(result);
        }
    }

    /**
     * 巴枪扫描完成，返回处理条码，刷新列表，显示扫描数量
     */
    private void doScan(String result) {

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }

        /** 条码在任务内*/
        for (int i = 0; i < mDifferScanDataList.size(); i++) {
            //运单对象
            DifferScanResponse.DifferScanEntity currentItemInfo = mDifferScanDataList.get(i);
            //判断子单是不是以主单开始的,减少循环次数
            if (!result.startsWith(currentItemInfo.getWaybillNo())) {
                continue;
            }
            //子单集合
            List<DifferScanResponse.DifferChild> childList = currentItemInfo.getStocktakingDiffreportInventoryVoList();
            //循环出单个子单
            for (DifferScanResponse.DifferChild childInfo : childList) {
                String childWayBillNO = childInfo.getWaybillChildNo();
                /** 扫描的单子发现在任务中*/
                if (result.equals(childWayBillNO)) {
                    Integer status = childInfo.getStatus();
                    if (status == 1) {
                        SoundVibratorManager.playSound(2);
                        showToast("重复扫描!");
                    } else {

                        /** 扫描数据插入到表中*/
                        if (insertScannedData(currentItemInfo, childWayBillNO) < 0) {
                            SoundVibratorManager.playSound(2);
                            showToast("插入数据库失败!");
                            return;
                        }

                        //未上传数据
                        totalNotUploadNum++;
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                        /** 设置该子单为已扫描的状态*/
                        childInfo.setStatus(1);
                        SoundVibratorManager.playSound(1);

                        /** 刷新增加的已扫描票和件*/
                        mTvScanedPiao.setText(DifferScanResponse.getTotalScannedPiao(mDifferScanDataList) + "");
                        mTvScanedJian.setText(DifferScanResponse.getTotalScannedJian(mDifferScanDataList) + "");

                        //上传数据
                        uploadData();
                    }
                    /** 更新当前行到第一行*/
                    mDifferScanDataList.remove(i);
                    mDifferScanDataList.add(0, currentItemInfo);
                    /**排序按照颜色：红，白，黄，绿*/
                    Collections.sort(mDifferScanDataList);
                    /** 刷新列表*/
                    mAdapter.notifyDataSetChanged();
                    return;
                }
            }
        }
        /** 条码不在任务内, 后面进行路由判断，是否强扫*/
        SoundVibratorManager.playSound(2);
        showToast("该条码不在配载单据内！");
    }

    /**
     * 插入已经扫描的数据到表中
     *
     * @param currentItemInfo 当前运单号的相关信息
     * @param waybillChildNo  当前子单的相关信息
     */
    private int insertScannedData(DifferScanResponse.DifferScanEntity currentItemInfo, String waybillChildNo) {
        DifferScanTable differScanTable = new DifferScanTable();
        differScanTable.setDiffreportNo(mDifferCode);
        differScanTable.setInputTime(Constants.GetScanTime());
        differScanTable.setInputUser(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        differScanTable.setIsUpload(0);
        differScanTable.setScanStatus(1);
        differScanTable.setOperTime(Constants.GetSysTime());
        differScanTable.setWaybillNo(currentItemInfo.getWaybillNo());
        differScanTable.setWaybillChildNo(waybillChildNo);
        int result = 0;
        try {
            result = mDifferScanTableDao.insert(differScanTable);
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.differ_scan_back:
                //返回按钮
                finish();
                break;
            case R.id.differ_scan_refresh:
                //刷新按钮
                loadData();
                break;
            case R.id.differ_scan_exec:
                //执行按钮
                if (mDifferScanDataList == null || mDifferScanDataList.size() <= 0) {
                    showToast(getString(R.string.tmp_no_data));
                    return;
                }
                if (!isScanBill()) {
                    showToast(getString(R.string.no_scan_num));
                    return;
                }
                MyDialog myDialog = new MyDialog(DifferScanActivity.this);
                myDialog.setIcon(R.drawable.alert);
                myDialog.setMessage("提交后将完成扫描，是否提交？");
                myDialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        completeTask();
                        dialog.dismiss();
                    }
                });
                myDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
                myDialog.show();
                break;
            default:
                break;
        }
    }

    private boolean isScanBill() {
        /** 条码在任务内*/
        for (int i = 0; i < mDifferScanDataList.size(); i++) {
            //运单对象
            DifferScanResponse.DifferScanEntity currentItemInfo = mDifferScanDataList.get(i);
            //子单集合
            List<DifferScanResponse.DifferChild> childList = currentItemInfo.getStocktakingDiffreportInventoryVoList();
            //循环出单个子单
            for (DifferScanResponse.DifferChild childInfo : childList) {
                String childWayBillNO = childInfo.getWaybillChildNo();
                /** 扫描的单子发现在任务中*/
                Integer status = childInfo.getStatus();
                if (status == 1) {
                    return true;
                }
            }
        }
        return false;
    }

    boolean isUploading = false;

    /**
     * 开始上传数据,调用接口
     */
    private void uploadData() {
        setScannerEnabled(false);
        if (isUploading) {
            Log.d("tag", "uploadData: 正在上传数据中...");
            return;
        }
        showPgDlg("正在提交...");
        //控制正在上传
        isUploading = true;

        //获取未上传的数据，然后判断
        final List<DifferScanTable> unUploadList = mDifferScanTableDao.getUnUploadDataList();
        if (unUploadList == null || unUploadList.size() <= 0) {
            showToast("没有未上传的数据!");
            isUploading = false;
            dismissPgDlg();
            setScannerEnabled(true);
            return;
        }

        //上传的json对象
        DifferUploadRequest differUploadRequestList = getBuildUploadData(unUploadList);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_DIFF_UPLOAD_SCAN)
                .setRequestObject(differUploadRequestList)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        isUploading = false;
                        dismissPgDlg();
                        setScannerEnabled(true);
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //更新未上传字段为已上传
                        for (DifferScanTable itemTable : unUploadList) {
                            itemTable.setIsUpload(1);
                            mDifferScanTableDao.updataItem(itemTable);
                        }

                        //减少未上传是数量
                        totalNotUploadNum = totalNotUploadNum - unUploadList.size();
                        if (totalNotUploadNum < 0) {
                            totalNotUploadNum = 0;
                        }
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                        isUploading = false;
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }
                });
    }

    /**
     * 上传数据的对象
     */
    private DifferUploadRequest getBuildUploadData(List<DifferScanTable> unUploadList) {

        DifferUploadRequest differUploadRequest = new DifferUploadRequest();
        List<DifferUploadRequest.DifferUploadEntity> mUpladList = new ArrayList<>();
        for (DifferScanTable itemTable : unUploadList) {
            //上传的具体子单信息的对象
            DifferUploadRequest.DifferUploadEntity differUploadEntity = new DifferUploadRequest.DifferUploadEntity();
            differUploadEntity.setWaybillNo(itemTable.getWaybillNo());
            differUploadEntity.setWaybillChildNo(itemTable.getWaybillChildNo());
            differUploadEntity.setDiffreportNo(mDifferCode);
            differUploadEntity.setInputTime(itemTable.getInputTime());
            differUploadEntity.setInputUser(itemTable.getInputUser());
            //加入对象的集合中
            mUpladList.add(differUploadEntity);
        }
        //list放到对象中
        differUploadRequest.setDiffreportDetailsVoList(mUpladList);
        return differUploadRequest;
    }

    /**
     * 点击提交, 如果有未提交的，先上传数据接口，再提交完成接口
     */
    private void completeTask() {
        final List<DifferScanTable> unUploadList = mDifferScanTableDao.getUnUploadDataList();
        if (unUploadList == null || unUploadList.size() <= 0) {
            //数据已经全部上传，就可以提交完成了
            lastCompleteUpload();
            return;
        }
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交扫描数据...");

        //最后去上传一次
        DifferUploadRequest differUploadRequest = getBuildUploadData(unUploadList);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_DIFF_UPLOAD_SCAN)
                .setRequestObject(differUploadRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        //更新未上传字段为已上传
                        for (DifferScanTable itemTable : unUploadList) {
                            itemTable.setIsUpload(1);
                            mDifferScanTableDao.updataItem(itemTable);
                        }

                        //减少未上传是数量
                        totalNotUploadNum = totalNotUploadNum - unUploadList.size();
                        if (totalNotUploadNum < 0) {
                            totalNotUploadNum = 0;
                        }
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                        dismissPgDlg();
                        setScannerEnabled(true);

                        //最后调用完成接口
                        lastCompleteUpload();
                    }
                });
    }

    /**
     * 完成的接口
     */
    private void lastCompleteUpload() {
        setScannerEnabled(false);
        showPgDlg("正在提交差异任务...");
        DifferCompleteRequest differCompleteRequest = new DifferCompleteRequest(mDifferCode, SharedPreferUtil.getInstance().getValue(Common.USER_CODE));

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_DIFF_COMPLETE)
                .setRequestObject(differCompleteRequest)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                        setScannerEnabled(true);
                        dismissPgDlg();
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        showToast("差异提交完成！");
                        setScannerEnabled(true);
                        SoundVibratorManager.playSound(1);
                        dismissPgDlg();
                        finish();
                    }
                });
    }
}
